from pymongo import MongoClient
import json
from datetime import datetime


class MongoDBManager:

    def __init__(self):
        self.db_name = 'mongo'
        self.db_pwd = 'mongo_test'

        try:
            self.client: MongoClient = MongoClient(
                'mongodb://43.153.140.179:27017/',
                username=self.db_name,
                password=self.db_pwd)
        except Exception as e:
            print(f"Failed to connect to MongoDB: {e}")

    def show_db_list(self) -> list:
        """获取所有数据库列表

        Returns:
            list: 数据库列表
        """
        db_list = self.client.list_database_names()
        print(db_list)
        return db_list

    def show_col_list(self, db_name: str) -> list:
        """获取所有集合列表

        Args:
            db_name (str): 数据库名称

        Returns:
            list: 集合列表
        """
        col_list = self.client[db_name].list_collection_names()
        print(col_list)
        return col_list

    def create_col(self, db_name: str, collection_name: str) -> None:
        """创建集合

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称
        """
        self.client[db_name].create_collection(collection_name)
        print(f"Collection '{collection_name}' created successfully.")
        self.show_col_list(db_name)

    def insert_one(self, db_name: str, collection_name: str,
                   document: dict) -> str:
        """插入单个文档

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称
            document (dict): 要插入的文档

        Returns:
            str: 插入的文档ID
        """
        result = self.client[db_name][collection_name].insert_one(document)
        return str(result.inserted_id)

    def find_one(self,
                 db_name: str,
                 collection_name: str,
                 query: dict = {}) -> dict:
        """
        查询单个文档

        不传查询条件时,默认查询所有

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称
            query (dict): 查询条件 Defaults to {}.

        Returns:
            dict: 查询结果
        """
        document = self.client[db_name][collection_name].find_one(query)
        return document

    def find_all(self,
                 db_name: str,
                 collection_name: str,
                 query: dict = {},
                 fields: dict = {}) -> list:
        """
        查询所有文档

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称

        Returns:
            list: 查询结果
        """
        documents = self.client[db_name][collection_name].find(query,fields)
        return list(documents)

    def update_one(self, db_name: str, collection_name: str, query: dict,
                   update_values: dict) -> int:
        """更新单个文档

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称
            query (dict): 查询条件
            update_values (dict): 更新的值

        Returns:
            int: 更新的文档计数
        """
        result = self.client[db_name][collection_name].update_one(
            query, {'$set': update_values})
        return result.modified_count

    def delete_one(self, db_name: str, collection_name: str,
                   query: dict) -> int:
        """删除单个文档

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称
            query (dict): 查询条件

        Returns:
            int: 删除的文档计数
        """
        result = self.client[db_name][collection_name].delete_one(query)
        return result.deleted_count

    def find_by_procode(self, db_name: str, collection_name: str,
                        procode: str) -> dict:
        """查找指定货号规格的商品 
        
        货号-规格

        Args:
            db_name (str): 数据库名称
            collection_name (str): 集合名称
            procode (str): 货号

        Returns:
            dict: _description_
        """
        product = self.find_one(db_name, collection_name,
                                {"product_code": procode})
        return product


if __name__ == "__main__":
    db_name = "productdb"
    db_col = 'mkl'
    sql_con = MongoDBManager()
    res = sql_con.find_all(db_name, db_col, {"item_code": "P816020"})
    print(res)
